import worker from '@ohos.worker';
import { Exchange, OperationType } from '../../workers/WorkerExchange';
import { dynamicLengthHexIPToHexIP, hexToIp } from '../NetWork/AddressUtil';
import { Info } from './GyroscopeControl';

const workerThread = new worker.ThreadWorker('entry/ets/workers/RemoteWorker.ts');

export class RemoteControl {
  constructor() {
  }

  public init() {
    let exchange = new Exchange(OperationType.create);
    workerThread.postMessage(exchange.toObject());
  }

  public setCallback(callback: (info: Info) => void) {
    workerThread.onmessage = (event) => {
      if (event.data == "close") {
        workerThread.onmessage = null;
        return;
      }
      let info = Info.fromObject(event.data);
      callback(info);
    }
  }

  public setAddress(str: string) {
    // let exchange = new Exchange(OperationType.setAddress);
    // exchange.ip = hexToIp(dynamicLengthHexIPToHexIP(str));
    // exchange.port = 10000;
    let exchange = new Exchange(OperationType.setAddress, hexToIp(dynamicLengthHexIPToHexIP(str)), 10000);
    workerThread.postMessage(exchange.toObject());
  }

  public startGyroscope(callback: (info: Info) => void) {
    let exchange = new Exchange(OperationType.startGyroscope);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
      let info = Info.fromObject(event.data);
      callback(info);

    }
  }

  public closeGyroscope() {
    let exchange = new Exchange(OperationType.stopGyroscope);
    workerThread.postMessage(exchange.toObject());
    workerThread.onmessage = (event) => {
      workerThread.onmessage = null;
    }
  }

  public close() {
    let exchange = new Exchange(OperationType.close);
    workerThread.postMessage(exchange.toObject());
  }
}